#include"Keti2Mgr.hpp"
#include"../Base/Concurrency/Lock.hpp"
#include<filesystem>
#include<fstream>
#include"rapidjson/document.h"
#include"MapApp.hpp"


namespace SC_SUN
{


    KeTi2Mgr::KeTi2Mgr(MapApp& app)
        :mApp(app)
    {

    }


    KeTi2Mgr::~KeTi2Mgr()
    {

    }


    void KeTi2Mgr::LoadData()
    {
        using namespace rapidjson;

        //加载c04数据
        std::string path = mApp.GetKeTi2Path() + "/C04.txt";
        int fileLen = std::filesystem::file_size(path);
        mKeti2C04.resize(fileLen);
        FILE* pf = fopen(path.c_str(), "wb");
        fread(mKeti2C04.data(), 1, fileLen, pf);
        fclose(pf);

        //加载clinfo
        path = mApp.GetKeTi2Path() + "/CLInfo.json";
        fileLen = std::filesystem::file_size(path);
        std::string buff;
        buff.resize(fileLen);
        pf = fopen(path.c_str(), "wb");
        fread(buff.data(), 1, fileLen, pf);
        fclose(pf);

        Document doc;
        doc.Parse(buff.data());
        auto array = doc.GetArray();
        for (int i = 0; i < array.Size(); i++)
        {
            auto obj = array[i].GetObj();
            ClInfo info;
            info.SAT_SN = obj["SAT_SN"].GetString();
            info.beta = obj["beta"].GetDouble();
            info.alpha = obj["alpha"].GetDouble();
            mCLinfos.insert({info.SAT_SN, info});
        }
    }


    KeTi2Mgr::Keti2Info KeTi2Mgr::GetData(const std::string& satSN)
    {
        Keti2Info ret;

        ret.keti2C04.resize(mKeti2C04.size());
        memcpy(ret.keti2C04.data(), mKeti2C04.data(), mKeti2C04.size());

        ret.info = mCLinfos.at(satSN);

        std::string reforbitFile = mApp.GetKeTi2Path() + "/keti2/" + satSN + "reforbit.txt";
        int fileLen = std::filesystem::file_size(reforbitFile);
        ret.reforbit.resize(fileLen);
        FILE* pf = fopen(reforbitFile.c_str(), "wb");
        fread(ret.reforbit.data(), 1, fileLen, pf);
        fclose(pf);

        return ret;
    }


    std::string KeTi2Mgr::GetDataJson(const std::string& satSN)
    {
        using namespace rapidjson;
        std::string ret;
        Keti2Info info = GetData(satSN);

        Document doc;
        doc.SetObject();

        Value InfoObj(kObjectType);
        InfoObj.AddMember(Value("SAT_SN", doc.GetAllocator()), Value(info.info.SAT_SN.data(), doc.GetAllocator()), doc.GetAllocator());
        InfoObj.AddMember(Value("SAT_STP", doc.GetAllocator()), Value(info.info.alpha), doc.GetAllocator());
        InfoObj.AddMember(Value("SAT_STP", doc.GetAllocator()), Value(info.info.beta), doc.GetAllocator());
        doc.AddMember(Value("info", doc.GetAllocator()), InfoObj, doc.GetAllocator());

        doc.AddMember(Value("keti2C04", doc.GetAllocator()), Value(info.keti2C04.data(), doc.GetAllocator()), doc.GetAllocator());
        doc.AddMember(Value("reforbit", doc.GetAllocator()), Value(info.reforbit.data(), doc.GetAllocator()), doc.GetAllocator());

        return ret;
    }
}